package net.board.action;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.board.db.BoardDAO;

 public class BoardListAction implements Action {
	 public ActionForward execute(HttpServletRequest request,HttpServletResponse response) throws Exception{
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		 
		BoardDAO boarddao=new BoardDAO();
		List boardlist=new ArrayList();
		
	  	int nowpage=1;
		int limit=10;
		int check = 0;
		String search = null;
		String searchword = null;
		
		String url = null;
		int number = Integer.parseInt(request.getParameter("number"));
		int listcount=boarddao.getListCount(); 
		
		if(request.getParameter("search")!=null && request.getParameter("searchword") != ""){
			search=request.getParameter("search");
		}
		
		if(request.getParameter("searchword")!= null && request.getParameter("searchword") != ""){
			searchword=request.getParameter("searchword");
			check = 1;
			listcount = boarddao.getListCount(search, searchword);
		}
		
		if(request.getParameter("nowpage")!= null){
			nowpage=Integer.parseInt(request.getParameter("nowpage"));
			
		}

		if(check == 1){
			boardlist = boarddao.getBoardList(nowpage,limit, search, searchword);
		}else{
			boardlist = boarddao.getBoardList(nowpage,limit); 
		}
System.out.println("글 천체수 = " + listcount);	
   		int maxpage=(int)((double)listcount/limit+0.95); 
   		
   		int startpage = (((int) ((double)nowpage / 10 + 0.9)) - 1) * 10 + 1;
   		
   		int endpage = maxpage;
   		
   		if (endpage>startpage+10-1) endpage=startpage+10-1;
   		
   		if(number == 1){
	   		url = "/Main/OldMain/Om_Main.jsp";
	   	}else if(number == 3){
	   		url = "/Main/admin/Ad_Main.jsp";
	   	}else{
	   		url = "/Main/YoungMain/Ym_Main.jsp";
	   	}
  		
   		String pagename = "/board/qna_board_list";
		request.setAttribute("page", pagename);
   		request.setAttribute("nowpage", nowpage);		 
   		request.setAttribute("maxpage", maxpage); 
   		request.setAttribute("startpage", startpage); 
   		request.setAttribute("endpage", endpage);     
		request.setAttribute("listcount",listcount); 
		request.setAttribute("boardlist", boardlist);
		request.setAttribute("number", number);
		request.setAttribute("search", search);
		request.setAttribute("searchword", searchword);
		
System.out.println("사용자 레벨 = " + number + " || 세팅 주소" + url);			
		ActionForward forward= new ActionForward();
	   	forward.setRedirect(false);
   		forward.setPath(url);
   		return forward;
	 }
 }